/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import entities.Logs;
import entities.RolesUsuarios;
import entities.RopaBlanca;
import entities.Usuarios;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.Beans;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.persistence.Query;
import javax.persistence.RollbackException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import logica.ExcelJTableExporter;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 *
 * @author Smuggler
 */
public class AltaUsuarios extends JPanel {

    private Logs logs;
    public static JFrame frame;
    private Usuarios usuario;
    private boolean editando = false;
    entities.Usuarios u;
    String password = "";

    public AltaUsuarios(Usuarios usuario) {
        initComponents();
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
        this.usuario = usuario;
    }

    private Integer getIDUsuario(String nombre) {
        Query queryIDUsuario;
        Usuarios usuario;
        queryIDUsuario = entityManager.createNamedQuery("Usuarios.findByNombre");
        queryIDUsuario.setParameter("nombre", nombre);
        usuario = (Usuarios) queryIDUsuario.getSingleResult();
        return usuario.getIdUsuario();
    }

    public JFrame getFrame() {
        return frame;
    }

    public void setFrame(JFrame frame) {
        AltaUsuarios.frame = frame;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SIAATPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT u FROM Usuarios u WHERE u.idUsuario !=1 ORDER BY  u.nombre ASC");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        usuariosQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT u FROM Usuarios u");
        usuariosList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : usuariosQuery.getResultList();
        rolesUsuariosQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT r FROM RolesUsuarios r");
        rolesUsuariosList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : rolesUsuariosQuery.getResultList();
        rolesUsuariosQuery1 = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT r FROM RolesUsuarios r");
        rolesUsuariosList1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : rolesUsuariosQuery1.getResultList();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        nombreLabel = new javax.swing.JLabel();
        passwordLabel = new javax.swing.JLabel();
        rolLabel = new javax.swing.JLabel();
        nombreField = new javax.swing.JTextField();
        guardarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();
        nuevoButton = new javax.swing.JButton();
        borrarButton = new javax.swing.JButton();
        PasswordField = new javax.swing.JPasswordField();
        rolComboBox = new javax.swing.JComboBox();
        ayudaLabel = new javax.swing.JLabel();
        exportarExcelButton = new javax.swing.JButton();

        FormListener formListener = new FormListener();

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${nombre}"));
        columnBinding.setColumnName("Nombre");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${rol.nombre}"));
        columnBinding.setColumnName("Rol");
        columnBinding.setColumnClass(String.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterTable.addMouseListener(formListener);
        masterScrollPane.setViewportView(masterTable);

        nombreLabel.setText("Nombre:");

        passwordLabel.setText("Password:");

        rolLabel.setText("Rol:");

        nombreField.setEnabled(false);
        nombreField.addKeyListener(formListener);

        guardarButton.setBackground(new java.awt.Color(1, 154, 210));
        guardarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        guardarButton.setForeground(new java.awt.Color(255, 255, 255));
        guardarButton.setText("Guardar");
        guardarButton.setEnabled(false);
        guardarButton.addActionListener(formListener);

        cancelarButton.setBackground(new java.awt.Color(1, 154, 210));
        cancelarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        cancelarButton.setForeground(new java.awt.Color(255, 255, 255));
        cancelarButton.setText("Cancelar");
        cancelarButton.setEnabled(false);
        cancelarButton.addActionListener(formListener);

        nuevoButton.setBackground(new java.awt.Color(1, 154, 210));
        nuevoButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        nuevoButton.setForeground(new java.awt.Color(255, 255, 255));
        nuevoButton.setText("Nuevo");
        nuevoButton.addActionListener(formListener);

        borrarButton.setBackground(new java.awt.Color(1, 154, 210));
        borrarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        borrarButton.setForeground(new java.awt.Color(255, 255, 255));
        borrarButton.setText("Borrar");
        borrarButton.setEnabled(false);
        borrarButton.addActionListener(formListener);

        PasswordField.setEnabled(false);
        PasswordField.addActionListener(formListener);

        rolComboBox.setEnabled(false);

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, rolesUsuariosList, rolComboBox, "");
        bindingGroup.addBinding(jComboBoxBinding);

        ayudaLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/help.png"))); // NOI18N
        ayudaLabel.addMouseListener(formListener);

        exportarExcelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/xls.png"))); // NOI18N
        exportarExcelButton.setText("Exportar");
        exportarExcelButton.addActionListener(formListener);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(masterScrollPane)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(nombreLabel)
                                .addGap(13, 13, 13)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(nombreField, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(passwordLabel))
                                    .addComponent(rolLabel))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(PasswordField, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
                                    .addComponent(rolComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(ayudaLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(exportarExcelButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(nuevoButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(borrarButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cancelarButton)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(guardarButton)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {borrarButton, cancelarButton, guardarButton, nuevoButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nombreLabel)
                    .addComponent(nombreField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(passwordLabel)
                    .addComponent(PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rolComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(rolLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 72, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(ayudaLabel)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(guardarButton)
                        .addComponent(cancelarButton)
                        .addComponent(borrarButton)
                        .addComponent(nuevoButton)
                        .addComponent(exportarExcelButton))))
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.KeyListener, java.awt.event.MouseListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == guardarButton) {
                AltaUsuarios.this.guardarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == cancelarButton) {
                AltaUsuarios.this.cancelarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == nuevoButton) {
                AltaUsuarios.this.nuevoButtonActionPerformed(evt);
            }
            else if (evt.getSource() == borrarButton) {
                AltaUsuarios.this.borrarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == PasswordField) {
                AltaUsuarios.this.PasswordFieldActionPerformed(evt);
            }
            else if (evt.getSource() == exportarExcelButton) {
                AltaUsuarios.this.exportarExcelButtonActionPerformed(evt);
            }
        }

        public void keyPressed(java.awt.event.KeyEvent evt) {
        }

        public void keyReleased(java.awt.event.KeyEvent evt) {
            if (evt.getSource() == nombreField) {
                AltaUsuarios.this.nombreFieldKeyReleased(evt);
            }
        }

        public void keyTyped(java.awt.event.KeyEvent evt) {
        }

        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == masterTable) {
                AltaUsuarios.this.masterTableMouseClicked(evt);
            }
        }

        public void mouseEntered(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == ayudaLabel) {
                AltaUsuarios.this.ayudaLabelMouseEntered(evt);
            }
        }

        public void mouseExited(java.awt.event.MouseEvent evt) {
        }

        public void mousePressed(java.awt.event.MouseEvent evt) {
        }

        public void mouseReleased(java.awt.event.MouseEvent evt) {
        }
    }// </editor-fold>//GEN-END:initComponents

    @SuppressWarnings("unchecked")
    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        refrescar();
    }//GEN-LAST:event_cancelarButtonActionPerformed
    private void limpiarBotones() {
        nombreField.setText("");
        PasswordField.setText("");
        rolComboBox.setSelectedIndex(-1);


    }

    private void refrescar() {
        entityManager.getTransaction().rollback();
        entityManager.getTransaction().begin();
        java.util.Collection data = query.getResultList();
        for (Object entity : data) {
            entityManager.refresh(entity);
        }
        list.clear();
        list.addAll(data);
        habilitarBotones(false);
        limpiarBotones();
    }
    private void borrarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_borrarButtonActionPerformed
        int respuesta = JOptionPane.showConfirmDialog(null, "Desea confirmar el borrado del Usuario?", "Borrado de Usuario", JOptionPane.YES_NO_OPTION);
        if (respuesta == JOptionPane.YES_OPTION) {
            int[] selected = masterTable.getSelectedRows();
            List<entities.Usuarios> toRemove = new ArrayList<entities.Usuarios>(selected.length);
            for (int idx = 0; idx < selected.length; idx++) {
                entities.Usuarios u = list.get(masterTable.convertRowIndexToModel(selected[idx]));
                toRemove.add(u);
                logs = new Logs();
                logs.setUsuario(usuario);
                logs.setearObservaciones("Borrado", "Usuarios", u.getIdUsuario(), "AltaUsuarios");
                entityManager.persist(logs);
                entityManager.remove(u);
            }
            list.removeAll(toRemove);
            entityManager.getTransaction().commit();
            entityManager.getTransaction().begin();


            refrescar();
        }
    }//GEN-LAST:event_borrarButtonActionPerformed
    private void habilitarBotones(boolean estado) {
        nombreField.setEnabled(estado);
        PasswordField.setEnabled(estado);
        rolComboBox.setEnabled(estado);
        masterTable.setEnabled(!estado);
        nuevoButton.setEnabled(!estado);
        borrarButton.setEnabled(estado);
        cancelarButton.setEnabled(estado);
        guardarButton.setEnabled(estado);


    }
    private void nuevoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoButtonActionPerformed

        habilitarBotones(true);
        borrarButton.setEnabled(false);
        rolComboBox.setSelectedIndex(0);
    }//GEN-LAST:event_nuevoButtonActionPerformed

    private String encriptar(String password) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        // Generamos una clave secreta. 
        String claveEncriptada = null;
        String claveOriginal = password;
        String semilla = "0123456789";


        SecretKeySpec desKey = new SecretKeySpec(new String((semilla.trim().concat("99999999")).substring(0, 8)).getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, desKey);
        byte[] claveEncriptadaBytes = cipher.doFinal(claveOriginal.getBytes());
        claveEncriptada = new BASE64Encoder().encode(claveEncriptadaBytes);

        return claveEncriptada;
    }

    private String decrypt(String encrypted) throws InvalidKeyException,
            NoSuchAlgorithmException, NoSuchPaddingException,
            IllegalBlockSizeException, BadPaddingException, IOException {
        String semilla = "0123456789";
        SecretKeySpec key = new SecretKeySpec(new String((semilla.trim().concat("99999999")).substring(0, 8)).getBytes(), "DES");
        // Get a cipher object.
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);

        //decode the BASE64 coded message
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] raw = decoder.decodeBuffer(encrypted);

        //decode the message
        byte[] stringBytes = cipher.doFinal(raw);

        //converts the decoded message to a String
        String clear = new String(stringBytes, "UTF8");

        return clear;
    }

    private boolean existeUsuario(String nombre) {
        int fila = 0;
        Query queryExisteUsuario = entityManager.createNamedQuery("Usuarios.findByNombre.count");
        queryExisteUsuario.setParameter("nombre", nombre);

        int count = ((Long) queryExisteUsuario.getSingleResult()).intValue();
        if ((count > 0)) {
            for (Usuarios usuarios : list) {
                if (masterTable.getSelectedRow() == fila) {
                } else {
                    if (usuarios.getNombre().equals(nombre)) {
                        return true;
                    }

                }
                fila++;
            }

        }
        return false;
    }

    private void guardarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarButtonActionPerformed


        char[] pass = PasswordField.getPassword();
        password = new String(pass);
        try {
            password = encriptar(password);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(AltaUsuarios.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchPaddingException ex) {
            Logger.getLogger(AltaUsuarios.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeyException ex) {
            Logger.getLogger(AltaUsuarios.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalBlockSizeException ex) {
            Logger.getLogger(AltaUsuarios.class.getName()).log(Level.SEVERE, null, ex);
        } catch (BadPaddingException ex) {
            Logger.getLogger(AltaUsuarios.class.getName()).log(Level.SEVERE, null, ex);
        }
        if ("".equals(nombreField.getText()) || "".equals(new String(PasswordField.getPassword()))) {
            String guardarmensaje = "";
            if ("".equals(nombreField.getText())) {
                guardarmensaje = guardarmensaje + "                     Nombre\n";
            }
            if ("".equals(new String(PasswordField.getPassword()))) {
                guardarmensaje = guardarmensaje + "                     Password\n";
            }
            JOptionPane.showMessageDialog(this, "Complete los campos :\n" + guardarmensaje, "Atención", JOptionPane.ERROR_MESSAGE, null);

        } else {
            if (!existeUsuario(nombreField.getText())) {
                try {
                    if (!editando) {
                        u = new Usuarios();
                        entityManager.persist(u);
                        list.add(u);
                        int row = list.size() - 1;
                        masterTable.setRowSelectionInterval(row, row);
                        masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
                    }
                    u.setNombre(nombreField.getText().toUpperCase());
                    u.setPassword(password);
                    u.setRol((RolesUsuarios) rolComboBox.getSelectedItem());
                    logs = new Logs();
                    logs.setUsuario(usuario);
                    if (editando) {
                        entityManager.merge(u);
                        editando = false;
                    }
                    if (u.getIdUsuario() == null) {
                        entityManager.getTransaction().commit();
                        entityManager.getTransaction().begin();
                        Integer idUsuario = getIDUsuario(u.getNombre());
                        logs.setearObservaciones("Alta", "Usuarios", idUsuario, "AltaUsuarios");
                    } else {
                        logs.setearObservaciones("Modificación", "Usuarios", u.getIdUsuario(), "AltaUsuarios");
                    }
                    entityManager.persist(logs);
                    entityManager.getTransaction().commit();
                    entityManager.getTransaction().begin();
                    refrescar();
                } catch (RollbackException rex) {
                    if (rex.getMessage().contains("nombre_UNIQUE")) {
                        JOptionPane.showMessageDialog(this, "El usuario ya se encuentra registrado", "Atención", JOptionPane.ERROR_MESSAGE, null);

                    }
                    entityManager.getTransaction().begin();
                    List<entities.Usuarios> merged = new ArrayList<entities.Usuarios>(list.size());
                    for (entities.Usuarios u : list) {
                        merged.add(entityManager.merge(u));
                    }



                }
            } else {
                JOptionPane.showMessageDialog(this, "El usuario ya se encuentra registrado", "Atención", JOptionPane.ERROR_MESSAGE, null);
            }
        }

    }//GEN-LAST:event_guardarButtonActionPerformed

    private void PasswordFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PasswordFieldActionPerformed
    }//GEN-LAST:event_PasswordFieldActionPerformed

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        habilitarBotones(true);
        editando = true;
        u = list.get(masterTable.getSelectedRow());
        password = u.getPassword();
        nombreField.setText(u.getNombre());
        rolComboBox.setSelectedItem(u.getRol());
        try {
            PasswordField.setText(decrypt(password));
        } catch (InvalidKeyException ex) {
            Logger.getLogger(AltaUsuarios.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(AltaUsuarios.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchPaddingException ex) {
            Logger.getLogger(AltaUsuarios.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalBlockSizeException ex) {
            Logger.getLogger(AltaUsuarios.class.getName()).log(Level.SEVERE, null, ex);
        } catch (BadPaddingException ex) {
            Logger.getLogger(AltaUsuarios.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(AltaUsuarios.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_masterTableMouseClicked

    private void ayudaLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ayudaLabelMouseEntered
        ayudaLabel.setToolTipText("En esta pantalla usted podra agregar,\n editar y eliminar unidades de alojamiento");
    }//GEN-LAST:event_ayudaLabelMouseEntered

    private void nombreFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nombreFieldKeyReleased
        String texto = nombreField.getText().toUpperCase();
        nombreField.setText(texto);
    }//GEN-LAST:event_nombreFieldKeyReleased

    private void exportarExcelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportarExcelButtonActionPerformed
        new ExcelJTableExporter(masterTable, "Usuarios").export();
    }//GEN-LAST:event_exportarExcelButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPasswordField PasswordField;
    private javax.swing.JLabel ayudaLabel;
    private javax.swing.JButton borrarButton;
    private javax.swing.JButton cancelarButton;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JButton exportarExcelButton;
    private javax.swing.JButton guardarButton;
    private java.util.List<entities.Usuarios> list;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JTextField nombreField;
    private javax.swing.JLabel nombreLabel;
    private javax.swing.JButton nuevoButton;
    private javax.swing.JLabel passwordLabel;
    private javax.persistence.Query query;
    private javax.swing.JComboBox rolComboBox;
    private javax.swing.JLabel rolLabel;
    private java.util.List<entities.RolesUsuarios> rolesUsuariosList;
    private java.util.List<entities.RolesUsuarios> rolesUsuariosList1;
    private javax.persistence.Query rolesUsuariosQuery;
    private javax.persistence.Query rolesUsuariosQuery1;
    private java.util.List<entities.Usuarios> usuariosList;
    private javax.persistence.Query usuariosQuery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public static void main(Usuarios user) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AltaUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AltaUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AltaUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AltaUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        final Usuarios usuario = user;
        /*
         * Create and display the form
         */
        AltaUsuarios.frame = new JFrame();
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                frame.setContentPane(new AltaUsuarios(usuario));
                frame.pack();
                frame.setVisible(true);
                frame.setTitle("Sistema   -   Usuarios   -   SIAAT  ");
                frame.setIconImage(new ImageIcon(getClass().getResource("/images/logo.png")).getImage());
                frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                frame.addWindowListener(new WindowAdapter() {

                    public void windowClosing(WindowEvent e) {
                        if (frame != null) {
                            frame.setVisible(false);
                        }
                        frame = null;
                    }
                });
            }
        });
    }
}
